﻿using UnityEngine;

public class SpriteFramePlayer : MonoBehaviour
{
    private Sprite[] sprites;
    private int index;
    private float timer;
    private float duration;
    private SpriteRenderer spriteRenderer;
    private bool isInited;

    // 新增合图自动播放接口
    public string atlasName;
    public string spriteName;
    public int frameSecond = 24;

    public void Init(Sprite[] sprites, int framePerSecond = 24)
    {
        this.sprites = sprites;
        this.duration = 1.0f / framePerSecond;
        this.timer = 0;
        this.index = 0;
        this.isInited = this.sprites != null && this.spriteRenderer != null && this.sprites.Length > 0;
        if (!this.isInited)
            return;

        RefreshSprite();
    }

    private void Awake()
    {
        this.spriteRenderer = GetComponent<SpriteRenderer>();
        // if (!string.IsNullOrEmpty(atlasName) && !string.IsNullOrEmpty(spriteName))
        // {
        //    SpriteAtlasFrame.Instance.getSpriteAtlas(atlasName, spriteName, sprites =>
        //    {
        //        if (sprites != null)
        //        {
        //            Init(sprites, frameSecond);
        //        }
        //    });
        // }
    }

    private void Update()
    {
        if (!this.isInited)
            return;

        timer += Time.deltaTime;
        if (timer >= duration)
        {
            timer = 0;
            if (++index >= this.sprites.Length)
                index = 0;

            RefreshSprite();
        }
    }

    private void RefreshSprite()
    {
        this.spriteRenderer.sprite = this.sprites[this.index];
    }

    public void OnRecover()
    {
        enabled = false;
        if (spriteRenderer)
        {
            spriteRenderer.enabled = false;
        }
    }

    public void OnGet()
    {
        enabled = true;
        if (spriteRenderer)
        {
            spriteRenderer.enabled = true;
        }
    }
}
